<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    class="app-container"
  >
    <div class="flex-row">
      <!-- <z-tree
        ref="tree"
        v-model="deptList"
        varient="energy"
        node-key="id"
        @handleNodeClick="handleNodeClick"
        class="bg left"
      ></z-tree> -->
      <div class="right">
        <!-- <echars
          :radarData="radarData"
          :pieData="pieData"
          class="bg"
          @change="getStaticInfo"
        ></echars> -->
        <div>
          <aps-form
            :config="apsForm.formConfig"
            :model="apsForm.formData"
            :formRef="apsForm.formRef"
            :labelWidth="apsForm.labelWidth"
            ref="form"
            class="mt10"
          ></aps-form>

          <!-- <div class="flex">
            <el-radio-group v-model="staticsType">
              <el-radio :label="1">逐日</el-radio>
              <el-radio :label="2">逐月</el-radio>
              <el-radio :label="3">逐年</el-radio>
            </el-radio-group>
            <div class="title">{{ title }}</div>
          </div> -->
          <lb-table
            v-loading="$store.getters.loading"
            element-loading-text="拼命加载中"
            :summary-method="getSummaries"
            height="640"
            show-summary
            element-loading-spinner="el-icon-loading"
            element-loading-background="#a19f9fb0;"
            :column="tableData.column"
            :data="tableData.data"
            pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :pager-count="5"
            :current-page.sync="currentPage"
            :total="total"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @p-current-change="handleCurrentChange"
            class="lbTable"
          >
          </lb-table>
        </div>
      </div>
    </div>
    <!-- 反馈对话框 -->
    <el-dialog
      title="人工确认"
      :visible.sync="show"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="close('form')">取 消</el-button>
      </div>
    </el-dialog>
  </lb-layout>
</template>

<script>
import { list, getTypeStaticsTreeChart, energyconfirm } from "@/api/sub/index";
import { dealElectricity, addDate } from "@/utils/index";
import CascaderSelect from "@/components/Select/CascaderSelect";
import echars from "@/views/statistics/winddirection/components/static.vue";
import zTree from "@/components/zTree";
export default {
  dicts: [
    "subentry_type",
    "energy_type",
    "energy_subarea_type",
    "energy_family_splitting_type",
    "energy_subarea_child_type",
    "special_energy_consumption_type",
  ],
  name: "winddirection",
  components: {
    zTree,
    CascaderSelect,
    echars,
  },
  data() {
    return {
      show: false,
      energyComputeType: "",
      energyType: "",
      energySubareaChildType: "",
      buildingList: [],
      areaList: [],
      areaProps: {
        value: "areaId",
        children: "children",
        label: "name",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      parktreeProps: {
        value: "id",
        children: "childList",
        label: "name",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      form: {
        id: "",
        remark: "",
      },
      rules: {
        remark: [
          {
            required: true,
            message: "请输入备注",
          },
        ],
      },
      activeName: "2",
      options: [
        {
          value: "主要指标",
          label: "主要指标",
          children: [
            {
              value: 0,
              label: "综合能耗",
            },
            {
              value: 1,
              label: "建筑能耗",
            },
            {
              value: 2,
              label: "交通能耗",
            },
            {
              value: 3,
              label: "单位面积能耗",
            },
            {
              value: 4,
              label: "人均能耗",
            },
          ],
        },
        {
          value: "参考指标",
          label: "参考指标",
          children: [
            {
              value: 0,
              label: "总电耗",
            },
            {
              value: 1,
              label: "总水耗",
            },
            {
              value: 2,
              label: "单位面积电耗",
            },
            {
              value: 3,
              label: "人均能耗",
            },
          ],
        },
        {
          value: "特殊用能",
          label: "特殊用能",
          children: [
            {
              value: 0,
              label: "办公室",
            },
            {
              value: 1,
              label: "办事大厅",
            },
            {
              value: 2,
              label: "教室",
            },
            {
              value: 3,
              label: "门诊",
            },
            {
              value: 4,
              label: "手术室",
            },
            {
              value: 5,
              label: "数据中心",
            },
          ],
        },
      ],

      radarData: [], // 雷达图数据
      pieData: [], // 饼图数据
      deptList: [],
      deptId: "",
      title: "备注：当日24小时负载。",
      staticsType: 1,
      networksId: "",
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            date: {
              label: "日期范围:",
              typeName: "el-date-picker",
              type: "daterange",
              size: "small",
              "value-format": "yyyy-MM-dd",
              "start-placeholder": "请选择开始日期",
              "end-placeholder": "请选择结束日期",
            },
            sysDeptId: {
              label: "用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let formValue = that.$refs?.form?.getFieldsValue().sysDeptId;
                return (
                  <div>
                    <CascaderSelect
                      value={formValue}
                      values={formValue}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择用能单位"}
                      onInput={that.handlerLiandong}
                      filterable={true}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            energyType: {
              label: "能耗类型:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().energyType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择能耗类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("energyType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: parseInt(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            subentryType: {
              label: "能耗分项:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.subentry_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().subentryType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择能耗分项",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "subentryType",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: parseInt(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "deptName",
            label: "公共机构",
            minWidth: "150",
            showOverflowTooltip: true,
          },
          {
            prop: "parentName",
            label: "所属能耗管理部门",
            minWidth: "150",
            showOverflowTooltip: true,
          },
          {
            prop: "statisticsDate",
            label: "时间段",
            width: "130",
          },
          {
            prop: "usedKgce",
            label: "标准煤（kgce）",
            minWidth: 150,
          },
          {
            prop: "thisTimeValue",
            label: "用量",
            minWidth: 150,
            render: (h, scope) => {
              let text = scope.row.energyType === 0 ? "kwh" : "L";
              let num =
                scope.row.energyType === 0
                  ? dealElectricity(scope.row.thisTimeValue)
                  : dealElectricity(scope.row.thisTimeValue, 1000);
              return (
                <div>
                  {num} {text}
                </div>
              );
            },
          },
          {
            prop: "area",
            label: "用能面积（m²）",
            minWidth: 130,
            showOverflowTooltip: true,
          },
          {
            prop: "userNum",
            label: "用能人数",
            minWidth: 120,
            showOverflowTooltip: true,
          },
          {
            prop: "energyType",
            label: "能耗类型",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_type}
                    value={scope.row.energyType}
                  />
                </div>
              );
            },
          },
          // {
          //   prop: "thisTimeValue",
          //   label: "负载（kwh）",
          //   render: (h, params) => {
          //     let num = dealElectricity(params.row.thisTimeValue);
          //     return h("div", {}, num);
          //   },
          // },
          {
            prop: "confirmFlag",
            label: "状态",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let text = scope.row.confirmFlag == 0 ? "未确认" : "已确认";
              return <div>{text}</div>;
            },
          },
          {
            prop: "msg",
            label: "同比",
            minWidth: 120,
            showOverflowTooltip: true,
            render: (h, scope) => {
              if (this.staticsType === 3) {
                return <div>-</div>;
              } else {
                const { thisTimeValue, lastYearValue } = scope.row;
                const tb = thisTimeValue - lastYearValue;
                return (
                  <div class={tb >= 0 ? "red" : "green"}>
                    {tb >= 0 ? "+" : "-"}
                    {lastYearValue === 0
                      ? "0"
                      : tb === 0
                      ? "0"
                      : Math.abs(((tb / lastYearValue) * 100).toFixed(2))}
                    %
                  </div>
                );
              }
            },
          },
          {
            prop: "msg",
            label: "环比",
            minWidth: 120,
            showOverflowTooltip: true,
            render: (h, scope) => {
              const { thisTimeValue, lastTimeValue } = scope.row;
              const hb = thisTimeValue - lastTimeValue;
              return (
                <div class={hb >= 0 ? "red" : "green"}>
                  {hb >= 0 ? "+" : "-"}
                  {lastTimeValue === 0
                    ? "0"
                    : hb === 0
                    ? "0"
                    : Math.abs(((hb / lastTimeValue) * 100).toFixed(2))}
                  %
                </div>
              );
            },
          },
          {
            prop: "leader",
            label: "分管领导",
            minWidth: 100,
            showOverflowTooltip: true,
          },
          {
            prop: "equipmentPercent",
            label: "计量设备配备率",
            minWidth: 130,
            render: (h, scope) => {
              return <div>{scope.row.equipmentPercent + "%"}</div>;
            },
          },
          {
            prop: "locations",
            label: "物理位置",
            minWidth: 200,
            showOverflowTooltip: true,
            render: (h, scope) => {
              return h(
                "div",
                // 第三个参数
                scope?.row?.locations?.map((item) =>
                  h(
                    "div",
                    item.parkName +
                      item.buildingName +
                      item.facilitiesFloor +
                      "层"
                  )
                )
              );
            },
          },
          {
            prop: "energyFamilySplitting",
            label: "能耗分户",
            width: 150,
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_family_splitting_type}
                    value={scope.row.energyFamilySplitting}
                  />
                </div>
              );
            },
          },
          {
            prop: "energySubarea",
            label: "能耗分区",
            width: 120,
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_subarea_type}
                    value={scope.row.energySubarea}
                  />
                </div>
              );
            },
          },
          {
            prop: "subentryType",
            label: "能耗分项",
            minWidth: 120,
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.subentry_type}
                    value={scope.row.subentryType}
                  />
                </div>
              );
            },
          },
          {
            label: "操作",
            width: "120",
            fixed: "right",
            render: (h, scope) => {
              if (scope.row.confirmFlag == 0) {
                return (
                  <div>
                    {
                      <el-button
                        v-hasPermi={["statistics:type:confirm"]}
                        type="text"
                        size="small"
                        icon="el-icon-check"
                        onClick={() => {
                          this.handleConfirm(scope.row);
                        }}
                      >
                        确认
                      </el-button>
                    }
                  </div>
                );
              }
            },
          },
        ],
        data: [],
      },
      names: [],
      date: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
    };
  },
  // watch: {
  //   staticsType(val) {
  //     const arr = [
  //       "备注：当月日总体负载情况。",
  //       "备注：最近6个月总体负载情况。",
  //       "备注：最近6年总体负载情况。",
  //     ];
  //     this.title = arr[val - 1];
  //     this.handlerSearchDetail();
  //   },
  // },
  mounted() {
    // this.getStaticInfo(2);
    this.initData();
  },
  methods: {
    handlerLiandong(value) {
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      this.deptId = result;
      this.$refs?.form?.setFieldValue("sysDeptId", this.deptId);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property == "usedKgce") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (prev * 1000000 + curr * 1000000) / 1000000;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " kgce";
        } else if (column.property == "thisTimeValue") {
          let text = "";
          sums[index] = values.reduce((prev, curr) => {
            text = data[index].energyType === 0 ? "kwh" : "l";
            const value = Number(curr);
            if (!isNaN(value)) {
              return (prev * 1000000 + curr * 1000000) / 1000000;
            } else {
              return prev;
            }
          }, 0);
          sums[index] =
            text === "kwh"
              ? dealElectricity(sums[index])
              : dealElectricity(sums[index], 1000);
          sums[index] += text;
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    /** 人工确认 */
    handleConfirm(row) {
      this.show = true;
      const { remark, sysDeptId, id } = row;
      this.form.id = id;
      this.form.remark = remark;
      this.form.deptId = sysDeptId;
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    close() {
      this.resetForm("form");
      this.show = false;
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const [startDate, endDate] = this.date || [];
          const data = {
            ...this.form,
            confirmDate: endDate,
          };
          energyconfirm(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.close();
              this.getStaticInfo(this.activeName);
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!300113");
            });
        }
      });
    },
    changeTab(val) {
      this.handleReset();
    },
    change(val) {
      this.names = val[val.length - 1];
    },
    getStaticInfo(val) {
      let that = this;
      getTypeStaticsTreeChart({
        type: val,
      })
        .then((res) => {
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            that.radarData = arr.map((item) => {
              item.name = that.dictEscape(item.nameType, val);
              return item;
            });
            that.pieData =
              val === 2
                ? arr[0].children.map((it) => {
                    it.name = that.subDict(
                      it.nameType,
                      "energy_subarea_child_type"
                    );
                    return it;
                  })
                : val === 3
                ? arr[0].children.map((it) => {
                    it.name = that.subDict(it.nameType, "subentry_type");
                    return it;
                  })
                : [];
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300112");
        });
    },
    subDict(val, dict) {
      let data = this.dict.type[dict].find((item) => item.value == val);
      return data?.label || "";
    },
    dictEscape(val, type) {
      let list;
      if (type == 1) {
        list = this.dict.type.energy_family_splitting_type;
      } else if (type == 2) {
        list = this.dict.type.energy_subarea_type;
      } else if (type == 3) {
        list = this.dict.type.energy_type;
      } else if (type == 4) {
        list = this.dict.type.subentry_type;
      }
      let data = list.find((item) => item.value == val);
      return data?.label || "";
    },
    handleNodeClick(data) {
      this.deptId = data.id;
      this.handlerSearchDetail();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
        // ways: this.staticsType,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows.map((item) => {
            let str = "";
            if (that.activeName == 1) {
              const [startDate, endDate] = that.date || [];
              if (startDate && endDate) {
                str = startDate + " ~ " + endDate;
              }
            } else {
              const [startDate, endDate] =
                that.$refs?.form?.getFieldsValue().date || [];
              if (startDate && endDate) {
                str = startDate + " ~ " + endDate;
              }
            }
            item.statisticsDate = str || addDate(new Date(), -1);
            return item;
          });
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300111");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      let data;
      if (this.activeName == 2) {
        const { date, ...other } = this.$refs?.form?.getFieldsValue();
        const [startDate, endDate] =
          this.$refs?.form?.getFieldsValue().date || [];
        data = {
          ...other,
          // networksId: this.networksId,
          endDate,
          startDate,
          deptId: this.deptId,
        };
      } else {
        // let energyComputeType = null;
        // let energyType = null;
        // let energySubareaChildType = null;
        // if (this.names == "建筑能耗") {
        //   energyComputeType = 1;
        // } else if (this.names == "交通能耗") {
        //   energyComputeType = 2;
        // } else if (this.names == "单位面积能耗") {
        //   energyComputeType = 3;
        // } else if (this.names == "人均能耗") {
        //   energyComputeType = 4;
        // } else if (this.names == "总电耗") {
        //   energyType = 0;
        // } else if (this.names == "总水耗") {
        //   energyType = 1;
        // } else if (this.names == "单位面积电耗") {
        //   energyType = 0;
        //   energyComputeType = 3;
        // } else if (this.names == "人均电耗") {
        //   energyType = 0;
        //   energyComputeType = 4;
        // } else if (this.names == "办公室") {
        //   energySubareaChildType = 0;
        // } else if (this.names == "办事大厅") {
        //   energySubareaChildType = 1;
        // } else if (this.names == "教室") {
        //   energySubareaChildType = 2;
        // } else if (this.names == "门诊") {
        //   energySubareaChildType = 3;
        // } else if (this.names == "手术室") {
        //   energySubareaChildType = 4;
        // } else if (this.names == "数据中心") {
        //   energySubareaChildType = 5;
        // }
        const [startDate, endDate] = this.date || [];
        data = {
          energyComputeType: this.energyComputeType,
          energyType: this.energyType,
          energySubareaChildType: this.energySubareaChildType,
          startDate,
          buildingId: this.buildingList[this.buildingList.length - 1],
          areaId: this.areaList[this.areaList.length - 1],
          endDate,
          deptId: this.deptId,
        };
      }
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.energyComputeType = "";
      this.energyType = "";
      this.energySubareaChildType = "";
      this.buildingList = [];
      this.areaList = [];
      this.deptId = "";
      this.deptList = [];
      this.networksId = "";
      // this.staticsType = 1;
      this.date = [];
      // this.names = [];
      // this.$refs.tree.$refs.tree.setCurrentKey(null);
      // this.$refs?.form?.setFieldValue("sysDeptId", null);
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
  },
};
</script>
<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";

::v-deep .flex-row {
  display: flex;

  .left {
    width: 220px;
    margin-right: 20px;
    max-height: 800px;

    .el-tree {
      @include scrollBar2;
    }
  }

  .right {
    flex: 1;
    width: 100%;
    overflow: auto;

    .lbTable {
      overflow: auto;
      @include scrollBar2;
    }
  }
}

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .el-radio {
    margin-right: 100px;
  }

  .title {
    color: #22568f;
    font-size: 14px;
  }
}

::v-deep .red {
  color: red;
}

::v-deep .green {
  color: rgb(56, 199, 56);
}
</style>
